package com.zeno.chinesecalendar.excel;

import com.zeno.chinesecalendar.BenderSelector;
import com.zeno.chinesecalendar.SimpleCalendar;
import org.apache.poi.ss.usermodel.*;

import java.text.MessageFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

/**
 * @author zeno.w
 * @date 2021/11/24 23:59
 */
public class ExcelExporter {

     private static final String[] TWO_HOURS = new String[]{"23-1","1-3","3-5","5-7","7-9","9-11","11-13","13-15",
             "15-17","17-19","19-21","21-23"};

     public static void export(int year) throws ParseException {

          Calendar exportDate = Calendar.getInstance();
          exportDate.set(Calendar.YEAR,year);

          YearWorkBook workBook = new YearWorkBook(year);
          List<SimpleCalendar.Element> days;
          for (int i = 0; i < 12; ++i){
               exportDate.set(Calendar.MONTH, i);
               days = SimpleCalendar.getMonthCalendar(exportDate);
               addMonthSheet(workBook,days);
          }

          workBook.flush();
     }

     private static void addMonthSheet(YearWorkBook ywb,List<SimpleCalendar.Element> days){

          MonthSheet monthSheet = ywb.addMonthSheet(days.get(0).getsMonth());

          Iterator<SimpleCalendar.Element> iterDays = days.iterator();
          for (int i=1;iterDays.hasNext(); i += 2){
               SimpleCalendar.Element day = iterDays.next();
               Row dayRow = monthSheet.addDayRow(i);
               String dayCellValue = MessageFormat.format("{3}日\r\n{0}年{1}月{2}日",day.getcYear(),day.getcMonth(),day.getcDay(),day.getsDay());
               monthSheet.addDayCell(dayRow,dayCellValue);

               Row eightTrigramsPositionCell = monthSheet.addEightTrigramRow(i + 1);
               for (short j=0,hour=0; hour < 24; hour +=2,++j){
                    String hourSemBranch = SimpleCalendar.getSemBranchHour(day.getcDay().charAt(0), hour);

                    // 23-1时(甲子)
                    String hourCellValue = MessageFormat.format("{0}时({1})", TWO_HOURS[j],hourSemBranch);
                    monthSheet.addHourCell(dayRow,j+1,hourCellValue);

                    // 阵门
                    String eightTrigramPositionCelValue = BenderSelector.getPosition(day.getcYear(),day.getcMonth(),
                            day.getcDay(),hourSemBranch);
                    monthSheet.addHourCell(eightTrigramsPositionCell,j+1,eightTrigramPositionCelValue);
               }
          }
     }
     public static void main(String[] args) throws ParseException {
          for (int year = 2021; year <= 2100; ++year)
               ExcelExporter.export(year);
     }
}
